package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderServiceImpl elderService;
    @Autowired
    private BedServiceImpl bedService;
    @Autowired
    private ContractServiceImpl contractService;
    @Autowired
    private CheckInConfigServiceImpl checkInConfigService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已经入住
        //select * from elder where idcardno= ?
        Elder newElder = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .one();
        if (newElder != null && newElder.getStatus()==1){
            throw new RuntimeException("该老人已经入住");
        }
        //更新床位状态为已入住
        //update bed set bed_status = 1 where id =?
        Bed DBbed = new Bed();
        DBbed.setBedStatus(1);
        DBbed.setId(dto.getCheckInConfigDto().getBedId());
        bedService.updateById(DBbed);
        //新增或更新老人
        Elder elder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        elder.setStatus(1);
        elder.setBedId(dto.getCheckInConfigDto().getBedId());
        elder.setBedNumber(bedService.selectBedById(dto.getCheckInConfigDto().getBedId()).getBedNumber());
        elderService.saveOrUpdate(elder);
        //新增签约办理
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT"+ IdUtil.fastUUID());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(LocalDateTime.now().isAfter(startDate)?1:0);

        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);

        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        this.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setRemark(checkIn.getRemark());
        checkInConfigService.save(checkInConfig);
    }

    @Override
    public CheckInDetailVo getAllById(Long id) {
        //Elder
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Elder byId = elderService.getById(checkIn.getElderId());
        CheckInElderVo checkInElderVo1 = BeanUtil.toBean(byId, CheckInElderVo.class);
        checkInDetailVo.setCheckInElderVo(checkInElderVo1);
        //elderFamilyVoList
        String remark = checkIn.getRemark();
        JSONArray jsonArray = JSON.parseArray(remark);
        List<ElderFamilyVo> javaList = jsonArray.toJavaList(ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(javaList);
        //CheckInConfig
        CheckInConfig one = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, id).one();
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(one, CheckInConfigVo.class);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //contract
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId, checkIn.getElderId()).one();
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;

    }
}
